package view;

import domein.Client;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

/**
 * @author Colin Bundervoet
 * @author Jeroen Pattyn
 * @author Bram Schotte
 * @author Lucas Van Overberghe
 */
public class ClientForm extends javax.swing.JFrame {

    /**
     * Creates new form clientForm
     */
    private Client client;
    private List<String> users;

    public List<String> getUsers() {
        return users;
    }

    public void setUsers(List<String> users) {
        this.users = users;
    }

    public ClientForm() {
        users = new ArrayList<>();
        initComponents();
        setLocationRelativeTo(null);
    }

    public JTextArea getChatTextArea() {
        return chatTextArea;
    }

    public void setChatTextArea(JTextArea chatTextArea) {
        this.chatTextArea = chatTextArea;
    }

    public JTextArea getInputChatArea() {
        return inputChatArea;
    }

    public JButton getSendButton() {
        return sendButton;
    }

    public JList getOnlineUsersList() {
        return onlineUsersList;
    }

    public void setInputChatArea(JTextArea inputChatArea) {
        this.inputChatArea = inputChatArea;
    }

    public JTextField getUsernameField() {
        return usernameField;
    }

    public void setUsernameField(JTextField usernameField) {
        this.usernameField = usernameField;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        usernameLabel = new javax.swing.JLabel();
        usernameField = new javax.swing.JTextField();
        connectButton = new javax.swing.JButton();
        disconnectButton = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        chatTextArea = new javax.swing.JTextArea();
        jScrollPane3 = new javax.swing.JScrollPane();
        inputChatArea = new javax.swing.JTextArea();
        sendButton = new javax.swing.JButton();
        serverLabel = new javax.swing.JLabel();
        serverField = new javax.swing.JTextField();
        portLabel = new javax.swing.JLabel();
        portField = new javax.swing.JTextField();
        backToMenuButton = new javax.swing.JButton();
        jScrollPane4 = new javax.swing.JScrollPane();
        onlineUsersList = new javax.swing.JList();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("ChIrc");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setResizable(false);

        usernameLabel.setText("Username");

        connectButton.setText("Connect");
        connectButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connectButtonActionPerformed(evt);
            }
        });

        disconnectButton.setText("Disconnect");
        disconnectButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                disconnectButtonActionPerformed(evt);
            }
        });

        chatTextArea.setEditable(false);
        chatTextArea.setColumns(20);
        chatTextArea.setLineWrap(true);
        chatTextArea.setRows(5);
        jScrollPane2.setViewportView(chatTextArea);

        inputChatArea.setColumns(20);
        inputChatArea.setRows(5);
        inputChatArea.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                inputChatAreaKeyPressed(evt);
            }
        });
        jScrollPane3.setViewportView(inputChatArea);

        sendButton.setText("Send");
        sendButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendButtonActionPerformed(evt);
            }
        });

        serverLabel.setText("Server");

        serverField.setText("localhost");
        serverField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                serverFieldActionPerformed(evt);
            }
        });

        portLabel.setText("Port");

        portField.setText("5000");

        backToMenuButton.setText("Menu");
        backToMenuButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                backToMenuButtonActionPerformed(evt);
            }
        });

        onlineUsersList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "No users"};
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        onlineUsersList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                onlineUsersListMousePressed(evt);
            }
        });
        jScrollPane4.setViewportView(onlineUsersList);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(serverLabel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(usernameLabel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(18, 18, 18)
                                .addComponent(usernameField, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGap(18, 18, 18)
                                .addComponent(serverField, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(27, 27, 27)
                        .addComponent(portLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(portField, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(connectButton, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(disconnectButton, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(backToMenuButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 505, Short.MAX_VALUE)
                            .addComponent(jScrollPane2))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                            .addComponent(sendButton, javax.swing.GroupLayout.DEFAULT_SIZE, 205, Short.MAX_VALUE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(serverLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(serverField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(portLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(portField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(connectButton)
                    .addComponent(disconnectButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(usernameLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(usernameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(backToMenuButton))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 222, Short.MAX_VALUE)
                    .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 222, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(sendButton, javax.swing.GroupLayout.DEFAULT_SIZE, 84, Short.MAX_VALUE)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void connectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connectButtonActionPerformed
        String server = serverField.getText();
        String poort = portField.getText();
        String username = usernameField.getText();

        if (server.equals("") || poort.equals("") || username.equals("") || !poort.matches("[0-9]*")) {
            showInChat("Enter all the required fields please");
        } else {
            int port = Integer.parseInt(poort);
            client = new Client(server, port, username);
            client.setForm(this);
            Thread t = new Thread() {
                @Override
                public void run() {
                    client.connectClient();
                }
            };
            t.start();
        }
    }//GEN-LAST:event_connectButtonActionPerformed

    private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendButtonActionPerformed
        String message = getInputChatArea().getText();

        if (client == null || client.isConnected() == false) {
            showInChat("You are not connected");
            inputChatArea.setText("");
            inputChatArea.requestFocus();
        } else {
            client.display(message);
            inputChatArea.setText("");
            inputChatArea.requestFocus();
        }
    }//GEN-LAST:event_sendButtonActionPerformed

    private void serverFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_serverFieldActionPerformed
    }//GEN-LAST:event_serverFieldActionPerformed

    private void disconnectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_disconnectButtonActionPerformed
        if (client == null || client.isConnected() == false) {
            showInChat("You are not connected");
        } else {
            client.disconnect();
            getUsernameField().setEditable(true);
        }
    }//GEN-LAST:event_disconnectButtonActionPerformed

    private void backToMenuButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backToMenuButtonActionPerformed
        if (client == null) {
            this.setVisible(false);
            new MenuForm().setVisible(true);
        } else if (!client.isConnected()) {
            client.disconnect();
            client = null;
            this.setVisible(false);
            new MenuForm().setVisible(true);
        } else {
            int choice = JOptionPane.showConfirmDialog(null, "You will be disconnected when you go back to the menu. Continue?", "Exit", JOptionPane.YES_NO_OPTION);

            if (choice == JOptionPane.YES_OPTION) {
                client.disconnect();
                client = null;
                this.setVisible(false);
                new MenuForm().setVisible(true);
            } else {
            }
        }
    }//GEN-LAST:event_backToMenuButtonActionPerformed

    private void inputChatAreaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_inputChatAreaKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            sendButton.doClick();
        }

    }//GEN-LAST:event_inputChatAreaKeyPressed

    private void onlineUsersListMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_onlineUsersListMousePressed
        JPopupMenu popupMenu = new JPopupMenu();
        popupMenu.add(kickButton = new JMenuItem("kick"));
        popupMenu.add(whoisButton = new JMenuItem("whois"));
        popupMenu.add(opButton = new JMenuItem("Set op"));
        popupMenu.add(deopButton = new JMenuItem("De-op"));
        popupMenu.add(banButton = new JMenuItem("ban"));
        kickButton.addActionListener(new ButtonAction());
        whoisButton.addActionListener(new ButtonAction());
        banButton.addActionListener(new ButtonAction());
        opButton.addActionListener(new ButtonAction());
        deopButton.addActionListener(new ButtonAction());

        if (SwingUtilities.isRightMouseButton(evt) && !onlineUsersList.isSelectionEmpty() && onlineUsersList.locationToIndex(evt.getPoint()) == onlineUsersList.getSelectedIndex()) {
            popupMenu.show(onlineUsersList, evt.getX(), evt.getY());
        }

    }//GEN-LAST:event_onlineUsersListMousePressed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ClientForm().setVisible(true);
            }
        });
    }

    public void showInChat(String message) {
        SimpleDateFormat date = new SimpleDateFormat();
        String time = date.format(new Date());
        getChatTextArea().append(time + ": " + message + "\n");
        JScrollBar s = jScrollPane2.getVerticalScrollBar();
        s.setValue(s.getMaximum());
    }

    public JScrollPane getjScrollPane2() {
        return jScrollPane2;
    }

    class ButtonAction implements ActionListener {
        public void actionPerformed(ActionEvent evt) {
            if (client == null || client.isConnected() == false) {
                showInChat("You are not connected");
                inputChatArea.setText("");
                inputChatArea.requestFocus();
            } else {
                if (evt.getSource() == kickButton) {
                    client.display("/kick " + onlineUsersList.getSelectedValue().toString());
                } else if (evt.getSource() == banButton) {
                    client.display("/ban " + onlineUsersList.getSelectedValue().toString());
                } else if (evt.getSource() == opButton) {
                    client.display("/op " + onlineUsersList.getSelectedValue().toString());
                } else if (evt.getSource() == deopButton) {
                    client.display("/deop " + onlineUsersList.getSelectedValue().toString());
                } else if (evt.getSource() == whoisButton) {
                    client.display("/whois " + onlineUsersList.getSelectedValue().toString());
                }
            }
        }
    }
    private JMenuItem kickButton;
    private JMenuItem whoisButton;
    private JMenuItem opButton;
    private JMenuItem deopButton;
    private JMenuItem banButton;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton backToMenuButton;
    private javax.swing.JTextArea chatTextArea;
    private javax.swing.JButton connectButton;
    private javax.swing.JButton disconnectButton;
    private javax.swing.JTextArea inputChatArea;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JList onlineUsersList;
    private javax.swing.JTextField portField;
    private javax.swing.JLabel portLabel;
    private javax.swing.JButton sendButton;
    private javax.swing.JTextField serverField;
    private javax.swing.JLabel serverLabel;
    private javax.swing.JTextField usernameField;
    private javax.swing.JLabel usernameLabel;
    // End of variables declaration//GEN-END:variables
}
